import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import sqlite3
from datetime import datetime
import random

class DroneDeliverySystem:
    def __init__(self, root):
        self.root = root
        self.root.title("无人机快递派送管理系统")
        self.root.geometry("1000x700")
        self.root.configure(bg='#f0f8ff')
        
        # 创建数据库连接
        self.conn = sqlite3.connect('dronedelivery.db')
        self.cursor = self.conn.cursor()
        
        # 创建数据库表
        self.create_tables()
        
        # 创建标签页
        self.tab_control = ttk.Notebook(root)
        
        # 无人机管理标签页
        self.drone_tab = ttk.Frame(self.tab_control)
        self.tab_control.add(self.drone_tab, text='无人机管理')
        
        # 站点管理标签页
        self.site_tab = ttk.Frame(self.tab_control)
        self.tab_control.add(self.site_tab, text='站点管理')
        
        # 订单管理标签页
        self.order_tab = ttk.Frame(self.tab_control)
        self.tab_control.add(self.order_tab, text='订单管理')
        
        # 系统信息标签页
        self.info_tab = ttk.Frame(self.tab_control)
        self.tab_control.add(self.info_tab, text='系统信息')
        
        self.tab_control.pack(expand=1, fill='both')
        
        # 初始化各个标签页
        self.init_drone_tab()
        self.init_site_tab()
        self.init_order_tab()
        self.init_info_tab()
        
        # 加载初始数据
        self.load_drones()
        self.load_sites()
        self.load_orders()
        
        # 绑定关闭窗口事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
    
    def create_tables(self):
        """创建数据库表"""
        # 无人机型号表
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS drones (
                            id INTEGER PRIMARY KEY,
                            model TEXT NOT NULL,
                            max_weight REAL NOT NULL,
                            max_range INTEGER NOT NULL,
                            status TEXT NOT NULL
                            )''')
        
        # 站点表
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS sites (
                            id INTEGER PRIMARY KEY,
                            name TEXT NOT NULL,
                            location TEXT NOT NULL,
                            capacity INTEGER NOT NULL
                            )''')
        
        # 订单表
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS orders (
                            id INTEGER PRIMARY KEY,
                            order_number TEXT NOT NULL,
                            sender TEXT NOT NULL,
                            receiver TEXT NOT NULL,
                            weight REAL NOT NULL,
                            origin_site INTEGER NOT NULL,
                            destination_site INTEGER NOT NULL,
                            status TEXT NOT NULL,
                            created_at TEXT NOT NULL,
                            FOREIGN KEY (origin_site) REFERENCES sites (id),
                            FOREIGN KEY (destination_site) REFERENCES sites (id)
                            )''')
        
        self.conn.commit()
    
    def init_drone_tab(self):
        """初始化无人机管理标签页"""
        # 标题
        title_label = tk.Label(self.drone_tab, text="无人机型号管理", font=("Arial", 16, "bold"), bg="#f0f8ff")
        title_label.pack(pady=10)
        
        # 控制按钮框架
        btn_frame = tk.Frame(self.drone_tab, bg="#f0f8ff")
        btn_frame.pack(pady=10)
        
        # 按钮
        add_btn = tk.Button(btn_frame, text="增加型号", command=self.add_drone, width=15, bg="#4CAF50", fg="white")
        add_btn.grid(row=0, column=0, padx=5)
        
        edit_btn = tk.Button(btn_frame, text="更改型号", command=self.edit_drone, width=15, bg="#2196F3", fg="white")
        edit_btn.grid(row=0, column=1, padx=5)
        
        delete_btn = tk.Button(btn_frame, text="删除型号", command=self.delete_drone, width=15, bg="#f44336", fg="white")
        delete_btn.grid(row=0, column=2, padx=5)
        
        # 无人机列表框架
        list_frame = tk.Frame(self.drone_tab)
        list_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 创建表格
        columns = ("id", "model", "max_weight", "max_range", "status")
        self.drone_tree = ttk.Treeview(list_frame, columns=columns, show="headings")
        
        # 设置列标题
        self.drone_tree.heading("id", text="ID")
        self.drone_tree.heading("model", text="型号")
        self.drone_tree.heading("max_weight", text="最大载重(kg)")
        self.drone_tree.heading("max_range", text="最大航程(km)")
        self.drone_tree.heading("status", text="状态")
        
        # 设置列宽
        self.drone_tree.column("id", width=50, anchor="center")
        self.drone_tree.column("model", width=150, anchor="center")
        self.drone_tree.column("max_weight", width=100, anchor="center")
        self.drone_tree.column("max_range", width=100, anchor="center")
        self.drone_tree.column("status", width=100, anchor="center")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.drone_tree.yview)
        self.drone_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.drone_tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
    
    def init_site_tab(self):
        """初始化站点管理标签页"""
        # 标题
        title_label = tk.Label(self.site_tab, text="站点管理", font=("Arial", 16, "bold"), bg="#f0f8ff")
        title_label.pack(pady=10)
        
        # 控制按钮框架
        btn_frame = tk.Frame(self.site_tab, bg="#f0f8ff")
        btn_frame.pack(pady=10)
        
        # 按钮
        add_btn = tk.Button(btn_frame, text="增加站点", command=self.add_site, width=15, bg="#4CAF50", fg="white")
        add_btn.grid(row=0, column=0, padx=5)
        
        edit_btn = tk.Button(btn_frame, text="更改站点", command=self.edit_site, width=15, bg="#2196F3", fg="white")
        edit_btn.grid(row=0, column=1, padx=5)
        
        delete_btn = tk.Button(btn_frame, text="删除站点", command=self.delete_site, width=15, bg="#f44336", fg="white")
        delete_btn.grid(row=0, column=2, padx=5)
        
        # 站点列表框架
        list_frame = tk.Frame(self.site_tab)
        list_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 创建表格
        columns = ("id", "name", "location", "capacity")
        self.site_tree = ttk.Treeview(list_frame, columns=columns, show="headings")
        
        # 设置列标题
        self.site_tree.heading("id", text="ID")
        self.site_tree.heading("name", text="站点名称")
        self.site_tree.heading("location", text="位置")
        self.site_tree.heading("capacity", text="容量")
        
        # 设置列宽
        self.site_tree.column("id", width=50, anchor="center")
        self.site_tree.column("name", width=150, anchor="center")
        self.site_tree.column("location", width=200, anchor="center")
        self.site_tree.column("capacity", width=100, anchor="center")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.site_tree.yview)
        self.site_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.site_tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
    
    def init_order_tab(self):
        """初始化订单管理标签页"""
        # 标题
        title_label = tk.Label(self.order_tab, text="订单管理", font=("Arial", 16, "bold"), bg="#f0f8ff")
        title_label.pack(pady=10)
        
        # 控制按钮框架
        btn_frame = tk.Frame(self.order_tab, bg="#f0f8ff")
        btn_frame.pack(pady=10)
        
        # 按钮
        add_btn = tk.Button(btn_frame, text="增加订单", command=self.add_order, width=15, bg="#4CAF50", fg="white")
        add_btn.grid(row=0, column=0, padx=5)
        
        delete_btn = tk.Button(btn_frame, text="删除订单", command=self.delete_order, width=15, bg="#f44336", fg="white")
        delete_btn.grid(row=0, column=1, padx=5)
        
        search_btn = tk.Button(btn_frame, text="查询订单", command=self.search_order, width=15, bg="#2196F3", fg="white")
        search_btn.grid(row=0, column=2, padx=5)
        
        # 订单列表框架
        list_frame = tk.Frame(self.order_tab)
        list_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 创建表格
        columns = ("id", "order_number", "sender", "receiver", "weight", "origin", "destination", "status", "created_at")
        self.order_tree = ttk.Treeview(list_frame, columns=columns, show="headings")
        
        # 设置列标题
        self.order_tree.heading("id", text="ID")
        self.order_tree.heading("order_number", text="订单号")
        self.order_tree.heading("sender", text="发件人")
        self.order_tree.heading("receiver", text="收件人")
        self.order_tree.heading("weight", text="重量(kg)")
        self.order_tree.heading("origin", text="起始站点")
        self.order_tree.heading("destination", text="目的站点")
        self.order_tree.heading("status", text="状态")
        self.order_tree.heading("created_at", text="创建时间")
        
        # 设置列宽
        self.order_tree.column("id", width=50, anchor="center")
        self.order_tree.column("order_number", width=120, anchor="center")
        self.order_tree.column("sender", width=100, anchor="center")
        self.order_tree.column("receiver", width=100, anchor="center")
        self.order_tree.column("weight", width=80, anchor="center")
        self.order_tree.column("origin", width=100, anchor="center")
        self.order_tree.column("destination", width=100, anchor="center")
        self.order_tree.column("status", width=100, anchor="center")
        self.order_tree.column("created_at", width=150, anchor="center")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.order_tree.yview)
        self.order_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.order_tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
    
    def init_info_tab(self):
        """初始化系统信息标签页"""
        # 标题
        title_label = tk.Label(self.info_tab, text="系统概览", font=("Arial", 16, "bold"), bg="#f0f8ff")
        title_label.pack(pady=20)
        
        # 统计信息框架
        stats_frame = tk.Frame(self.info_tab, bg="#f0f8ff")
        stats_frame.pack(pady=20)
        
        # 获取统计数据
        drone_count = self.cursor.execute("SELECT COUNT(*) FROM drones").fetchone()[0]
        site_count = self.cursor.execute("SELECT COUNT(*) FROM sites").fetchone()[0]
        order_count = self.cursor.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
        pending_orders = self.cursor.execute("SELECT COUNT(*) FROM orders WHERE status='待处理'").fetchone()[0]
        in_transit_orders = self.cursor.execute("SELECT COUNT(*) FROM orders WHERE status='运输中'").fetchone()[0]
        delivered_orders = self.cursor.execute("SELECT COUNT(*) FROM orders WHERE status='已送达'").fetchone()[0]
        
        # 创建统计信息标签
        tk.Label(stats_frame, text=f"无人机型号数量: {drone_count}", font=("Arial", 12), bg="#f0f8ff").grid(row=0, column=0, padx=20, pady=10, sticky="w")
        tk.Label(stats_frame, text=f"站点数量: {site_count}", font=("Arial", 12), bg="#f0f8ff").grid(row=1, column=0, padx=20, pady=10, sticky="w")
        tk.Label(stats_frame, text=f"订单总数: {order_count}", font=("Arial", 12), bg="#f0f8ff").grid(row=2, column=0, padx=20, pady=10, sticky="w")
        tk.Label(stats_frame, text=f"待处理订单: {pending_orders}", font=("Arial", 12), bg="#f0f8ff").grid(row=0, column=1, padx=20, pady=10, sticky="w")
        tk.Label(stats_frame, text=f"运输中订单: {in_transit_orders}", font=("Arial", 12), bg="#f0f8ff").grid(row=1, column=1, padx=20, pady=10, sticky="w")
        tk.Label(stats_frame, text=f"已送达订单: {delivered_orders}", font=("Arial", 12), bg="#f0f8ff").grid(row=2, column=1, padx=20, pady=10, sticky="w")
        
        # 分隔线
        separator = ttk.Separator(self.info_tab, orient='horizontal')
        separator.pack(fill='x', padx=20, pady=10)
        
        # 系统信息
        info_frame = tk.Frame(self.info_tab, bg="#f0f8ff")
        info_frame.pack(pady=20)
        
        tk.Label(info_frame, text="无人机快递派送管理系统", font=("Arial", 14, "bold"), bg="#f0f8ff").pack(pady=5)
        tk.Label(info_frame, text="版本: 2.0", font=("Arial", 12), bg="#f0f8ff").pack(pady=5)
        tk.Label(info_frame, text="开发日期: 2025-6-21", font=("Arial", 12), bg="#f0f8ff").pack(pady=5)
        tk.Label(info_frame, text="功能:", font=("Arial", 12, "bold"), bg="#f0f8ff").pack(pady=5)
        tk.Label(info_frame, text="- 无人机型号管理", font=("Arial", 11), bg="#f0f8ff").pack(anchor="w", padx=20)
        tk.Label(info_frame, text="- 站点管理", font=("Arial", 11), bg="#f0f8ff").pack(anchor="w", padx=20)
        tk.Label(info_frame, text="- 订单管理", font=("Arial", 11), bg="#f0f8ff").pack(anchor="w", padx=20)
    
    def load_drones(self):
        """加载无人机数据"""
        # 清空现有数据
        for item in self.drone_tree.get_children():
            self.drone_tree.delete(item)
        
        # 从数据库获取数据
        self.cursor.execute("SELECT * FROM drones")
        drones = self.cursor.fetchall()
        
        # 插入到表格中
        for drone in drones:
            self.drone_tree.insert("", "end", values=drone)
    
    def load_sites(self):
        """加载站点数据"""
        # 清空现有数据
        for item in self.site_tree.get_children():
            self.site_tree.delete(item)
        
        # 从数据库获取数据
        self.cursor.execute("SELECT * FROM sites")
        sites = self.cursor.fetchall()
        
        # 插入到表格中
        for site in sites:
            self.site_tree.insert("", "end", values=site)
    
    def load_orders(self):
        """加载订单数据"""
        # 清空现有数据
        for item in self.order_tree.get_children():
            self.order_tree.delete(item)
        
        # 从数据库获取数据
        self.cursor.execute("""
            SELECT orders.id, order_number, sender, receiver, weight, 
                   origin.name, destination.name, status, created_at
            FROM orders
            JOIN sites AS origin ON orders.origin_site = origin.id
            JOIN sites AS destination ON orders.destination_site = destination.id
        """)
        orders = self.cursor.fetchall()
        
        # 插入到表格中
        for order in orders:
            self.order_tree.insert("", "end", values=order)
    
    def add_drone(self):
        """增加无人机型号"""
        # 创建对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("增加无人机型号")
        dialog.geometry("400x300")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 表单框架
        form_frame = tk.Frame(dialog, padx=20, pady=20)
        form_frame.pack(fill="both", expand=True)
        
        # 表单字段
        tk.Label(form_frame, text="型号名称:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        model_entry = tk.Entry(form_frame, width=25)
        model_entry.grid(row=0, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="最大载重(kg):").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        weight_entry = tk.Entry(form_frame, width=25)
        weight_entry.grid(row=1, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="最大航程(km):").grid(row=2, column=0, padx=5, pady=5, sticky="e")
        range_entry = tk.Entry(form_frame, width=25)
        range_entry.grid(row=2, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="状态:").grid(row=3, column=0, padx=5, pady=5, sticky="e")
        status_var = tk.StringVar(value="可用")
        status_menu = ttk.Combobox(form_frame, textvariable=status_var, width=22)
        status_menu['values'] = ("可用", "维修中", "已停用")
        status_menu.grid(row=3, column=1, padx=5, pady=5)
        
        # 按钮框架
        btn_frame = tk.Frame(dialog, pady=10)
        btn_frame.pack()
        
        # 提交按钮
        submit_btn = tk.Button(btn_frame, text="提交", width=10, 
                             command=lambda: self.save_drone(
                                 model_entry.get(),
                                 weight_entry.get(),
                                 range_entry.get(),
                                 status_var.get(),
                                 dialog
                             ))
        submit_btn.pack(side="left", padx=10)
        
        # 取消按钮
        cancel_btn = tk.Button(btn_frame, text="取消", width=10, command=dialog.destroy)
        cancel_btn.pack(side="left", padx=10)
        
        dialog.mainloop()
    
    def save_drone(self, model, weight, max_range, status, dialog):
        """保存无人机数据"""
        if not model or not weight or not max_range:
            messagebox.showerror("错误", "所有字段都必须填写！")
            return
        
        try:
            weight = float(weight)
            max_range = int(max_range)
        except ValueError:
            messagebox.showerror("错误", "载重和航程必须是数字！")
            return
        
        # 插入数据库
        self.cursor.execute("""
            INSERT INTO drones (model, max_weight, max_range, status)
            VALUES (?, ?, ?, ?)
        """, (model, weight, max_range, status))
        self.conn.commit()
        
        messagebox.showinfo("成功", "无人机型号添加成功！")
        self.load_drones()
        dialog.destroy()
    
    def edit_drone(self):
        """更改无人机型号"""
        selected = self.drone_tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择一个无人机型号！")
            return
        
        item = self.drone_tree.item(selected[0])
        drone_id, model, max_weight, max_range, status = item['values']
        
        # 创建对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("更改无人机型号")
        dialog.geometry("400x300")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 表单框架
        form_frame = tk.Frame(dialog, padx=20, pady=20)
        form_frame.pack(fill="both", expand=True)
        
        # 表单字段
        tk.Label(form_frame, text="型号名称:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        model_entry = tk.Entry(form_frame, width=25)
        model_entry.insert(0, model)
        model_entry.grid(row=0, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="最大载重(kg):").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        weight_entry = tk.Entry(form_frame, width=25)
        weight_entry.insert(0, max_weight)
        weight_entry.grid(row=1, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="最大航程(km):").grid(row=2, column=0, padx=5, pady=5, sticky="e")
        range_entry = tk.Entry(form_frame, width=25)
        range_entry.insert(0, max_range)
        range_entry.grid(row=2, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="状态:").grid(row=3, column=0, padx=5, pady=5, sticky="e")
        status_var = tk.StringVar(value=status)
        status_menu = ttk.Combobox(form_frame, textvariable=status_var, width=22)
        status_menu['values'] = ("可用", "维修中", "已停用")
        status_menu.grid(row=3, column=1, padx=5, pady=5)
        
        # 按钮框架
        btn_frame = tk.Frame(dialog, pady=10)
        btn_frame.pack()
        
        # 提交按钮
        submit_btn = tk.Button(btn_frame, text="更新", width=10, 
                             command=lambda: self.update_drone(
                                 drone_id,
                                 model_entry.get(),
                                 weight_entry.get(),
                                 range_entry.get(),
                                 status_var.get(),
                                 dialog
                             ))
        submit_btn.pack(side="left", padx=10)
        
        # 取消按钮
        cancel_btn = tk.Button(btn_frame, text="取消", width=10, command=dialog.destroy)
        cancel_btn.pack(side="left", padx=10)
        
        dialog.mainloop()
    
    def update_drone(self, drone_id, model, weight, max_range, status, dialog):
        """更新无人机数据"""
        if not model or not weight or not max_range:
            messagebox.showerror("错误", "所有字段都必须填写！")
            return
        
        try:
            weight = float(weight)
            max_range = int(max_range)
        except ValueError:
            messagebox.showerror("错误", "载重和航程必须是数字！")
            return
        
        # 更新数据库
        self.cursor.execute("""
            UPDATE drones
            SET model=?, max_weight=?, max_range=?, status=?
            WHERE id=?
        """, (model, weight, max_range, status, drone_id))
        self.conn.commit()
        
        messagebox.showinfo("成功", "无人机型号更新成功！")
        self.load_drones()
        dialog.destroy()
    
    def delete_drone(self):
        """删除无人机型号"""
        selected = self.drone_tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择一个无人机型号！")
            return
        
        item = self.drone_tree.item(selected[0])
        drone_id, model, _, _, _ = item['values']
        
        if messagebox.askyesno("确认", f"确定要删除无人机型号 '{model}' 吗？"):
            # 从数据库删除
            self.cursor.execute("DELETE FROM drones WHERE id=?", (drone_id,))
            self.conn.commit()
            
            messagebox.showinfo("成功", "无人机型号删除成功！")
            self.load_drones()
    
    def add_site(self):
        """增加站点"""
        # 创建对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("增加站点")
        dialog.geometry("400x300")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 表单框架
        form_frame = tk.Frame(dialog, padx=20, pady=20)
        form_frame.pack(fill="both", expand=True)
        
        # 表单字段
        tk.Label(form_frame, text="站点名称:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        name_entry = tk.Entry(form_frame, width=25)
        name_entry.grid(row=0, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="位置:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        location_entry = tk.Entry(form_frame, width=25)
        location_entry.grid(row=1, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="容量:").grid(row=2, column=0, padx=5, pady=5, sticky="e")
        capacity_entry = tk.Entry(form_frame, width=25)
        capacity_entry.grid(row=2, column=1, padx=5, pady=5)
        
        # 按钮框架
        btn_frame = tk.Frame(dialog, pady=10)
        btn_frame.pack()
        
        # 提交按钮
        submit_btn = tk.Button(btn_frame, text="提交", width=10, 
                             command=lambda: self.save_site(
                                 name_entry.get(),
                                 location_entry.get(),
                                 capacity_entry.get(),
                                 dialog
                             ))
        submit_btn.pack(side="left", padx=10)
        
        # 取消按钮
        cancel_btn = tk.Button(btn_frame, text="取消", width=10, command=dialog.destroy)
        cancel_btn.pack(side="left", padx=10)
        
        dialog.mainloop()
    
    def save_site(self, name, location, capacity, dialog):
        """保存站点数据"""
        if not name or not location or not capacity:
            messagebox.showerror("错误", "所有字段都必须填写！")
            return
        
        try:
            capacity = int(capacity)
        except ValueError:
            messagebox.showerror("错误", "容量必须是整数！")
            return
        
        # 插入数据库
        self.cursor.execute("""
            INSERT INTO sites (name, location, capacity)
            VALUES (?, ?, ?)
        """, (name, location, capacity))
        self.conn.commit()
        
        messagebox.showinfo("成功", "站点添加成功！")
        self.load_sites()
        dialog.destroy()
    
    def edit_site(self):
        """更改站点"""
        selected = self.site_tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择一个站点！")
            return
        
        item = self.site_tree.item(selected[0])
        site_id, name, location, capacity = item['values']
        
        # 创建对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("更改站点信息")
        dialog.geometry("400x300")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 表单框架
        form_frame = tk.Frame(dialog, padx=20, pady=20)
        form_frame.pack(fill="both", expand=True)
        
        # 表单字段
        tk.Label(form_frame, text="站点名称:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        name_entry = tk.Entry(form_frame, width=25)
        name_entry.insert(0, name)
        name_entry.grid(row=0, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="位置:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        location_entry = tk.Entry(form_frame, width=25)
        location_entry.insert(0, location)
        location_entry.grid(row=1, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="容量:").grid(row=2, column=0, padx=5, pady=5, sticky="e")
        capacity_entry = tk.Entry(form_frame, width=25)
        capacity_entry.insert(0, capacity)
        capacity_entry.grid(row=2, column=1, padx=5, pady=5)
        
        # 按钮框架
        btn_frame = tk.Frame(dialog, pady=10)
        btn_frame.pack()
        
        # 提交按钮
        submit_btn = tk.Button(btn_frame, text="更新", width=10, 
                             command=lambda: self.update_site(
                                 site_id,
                                 name_entry.get(),
                                 location_entry.get(),
                                 capacity_entry.get(),
                                 dialog
                             ))
        submit_btn.pack(side="left", padx=10)
        
        # 取消按钮
        cancel_btn = tk.Button(btn_frame, text="取消", width=10, command=dialog.destroy)
        cancel_btn.pack(side="left", padx=10)
        
        dialog.mainloop()
    
    def update_site(self, site_id, name, location, capacity, dialog):
        """更新站点数据"""
        if not name or not location or not capacity:
            messagebox.showerror("错误", "所有字段都必须填写！")
            return
        
        try:
            capacity = int(capacity)
        except ValueError:
            messagebox.showerror("错误", "容量必须是整数！")
            return
        
        # 更新数据库
        self.cursor.execute("""
            UPDATE sites
            SET name=?, location=?, capacity=?
            WHERE id=?
        """, (name, location, capacity, site_id))
        self.conn.commit()
        
        messagebox.showinfo("成功", "站点信息更新成功！")
        self.load_sites()
        dialog.destroy()
    
    def delete_site(self):
        """删除站点"""
        selected = self.site_tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择一个站点！")
            return
        
        item = self.site_tree.item(selected[0])
        site_id, name, _, _ = item['values']
        
        # 检查该站点是否有关联的订单
        self.cursor.execute("SELECT COUNT(*) FROM orders WHERE origin_site=? OR destination_site=?", (site_id, site_id))
        order_count = self.cursor.fetchone()[0]
        
        if order_count > 0:
            messagebox.showerror("错误", "该站点有关联的订单，无法删除！")
            return
        
        if messagebox.askyesno("确认", f"确定要删除站点 '{name}' 吗？"):
            # 从数据库删除
            self.cursor.execute("DELETE FROM sites WHERE id=?", (site_id,))
            self.conn.commit()
            
            messagebox.showinfo("成功", "站点删除成功！")
            self.load_sites()
    
    def add_order(self):
        """增加订单"""
        # 获取站点列表
        self.cursor.execute("SELECT id, name FROM sites")
        sites = self.cursor.fetchall()
        site_dict = {name: id for id, name in sites}
        site_names = [name for id, name in sites]
        
        if not sites:
            messagebox.showerror("错误", "请先添加至少两个站点！")
            return
        
        # 创建对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("增加订单")
        dialog.geometry("500x400")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 表单框架
        form_frame = tk.Frame(dialog, padx=20, pady=20)
        form_frame.pack(fill="both", expand=True)
        
        # 表单字段
        tk.Label(form_frame, text="发件人:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        sender_entry = tk.Entry(form_frame, width=30)
        sender_entry.grid(row=0, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="收件人:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        receiver_entry = tk.Entry(form_frame, width=30)
        receiver_entry.grid(row=1, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="重量(kg):").grid(row=2, column=0, padx=5, pady=5, sticky="e")
        weight_entry = tk.Entry(form_frame, width=30)
        weight_entry.grid(row=2, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="起始站点:").grid(row=3, column=0, padx=5, pady=5, sticky="e")
        origin_var = tk.StringVar()
        origin_menu = ttk.Combobox(form_frame, textvariable=origin_var, width=27)
        origin_menu['values'] = site_names
        origin_menu.grid(row=3, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="目的站点:").grid(row=4, column=0, padx=5, pady=5, sticky="e")
        dest_var = tk.StringVar()
        dest_menu = ttk.Combobox(form_frame, textvariable=dest_var, width=27)
        dest_menu['values'] = site_names
        dest_menu.grid(row=4, column=1, padx=5, pady=5)
        
        # 按钮框架
        btn_frame = tk.Frame(dialog, pady=10)
        btn_frame.pack()
        
        # 提交按钮
        submit_btn = tk.Button(btn_frame, text="提交", width=10, 
                             command=lambda: self.save_order(
                                 sender_entry.get(),
                                 receiver_entry.get(),
                                 weight_entry.get(),
                                 origin_var.get(),
                                 dest_var.get(),
                                 site_dict,
                                 dialog
                             ))
        submit_btn.pack(side="left", padx=10)
        
        # 取消按钮
        cancel_btn = tk.Button(btn_frame, text="取消", width=10, command=dialog.destroy)
        cancel_btn.pack(side="left", padx=10)
        
        dialog.mainloop()
    
    def save_order(self, sender, receiver, weight, origin_name, dest_name, site_dict, dialog):
        """保存订单数据"""
        if not sender or not receiver or not weight or not origin_name or not dest_name:
            messagebox.showerror("错误", "所有字段都必须填写！")
            return
        
        if origin_name == dest_name:
            messagebox.showerror("错误", "起始站点和目的站点不能相同！")
            return
        
        try:
            weight = float(weight)
            if weight <= 0:
                messagebox.showerror("错误", "重量必须是正数！")
                return
        except ValueError:
            messagebox.showerror("错误", "重量必须是数字！")
            return
        
        origin_id = site_dict.get(origin_name)
        dest_id = site_dict.get(dest_name)
        
        if not origin_id or not dest_id:
            messagebox.showerror("错误", "站点选择无效！")
            return
        
        # 生成订单号
        order_number = f"ORD-{datetime.now().strftime('%Y%m%d%H%M%S')}-{random.randint(1000, 9999)}"
        
        # 插入数据库
        self.cursor.execute("""
            INSERT INTO orders (order_number, sender, receiver, weight, 
                              origin_site, destination_site, status, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        """, (order_number, sender, receiver, weight, origin_id, dest_id, "待处理", datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        self.conn.commit()
        
        messagebox.showinfo("成功", f"订单添加成功！\n订单号: {order_number}")
        self.load_orders()
        dialog.destroy()
    
    def delete_order(self):
        """删除订单"""
        selected = self.order_tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择一个订单！")
            return
        
        item = self.order_tree.item(selected[0])
        order_id, order_number, _, _, _, _, _, _, _ = item['values']
        
        if messagebox.askyesno("确认", f"确定要删除订单 '{order_number}' 吗？"):
            # 从数据库删除
            self.cursor.execute("DELETE FROM orders WHERE id=?", (order_id,))
            self.conn.commit()
            
            messagebox.showinfo("成功", "订单删除成功！")
            self.load_orders()
    
    def search_order(self):
        """查询订单"""
        # 创建对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("查询订单")
        dialog.geometry("400x200")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 表单框架
        form_frame = tk.Frame(dialog, padx=20, pady=20)
        form_frame.pack(fill="both", expand=True)
        
        # 表单字段
        tk.Label(form_frame, text="订单号:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        order_num_entry = tk.Entry(form_frame, width=25)
        order_num_entry.grid(row=0, column=1, padx=5, pady=5)
        
        tk.Label(form_frame, text="或发件人:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        sender_entry = tk.Entry(form_frame, width=25)
        sender_entry.grid(row=1, column=1, padx=5, pady=5)
        
        # 按钮框架
        btn_frame = tk.Frame(dialog, pady=10)
        btn_frame.pack()
        
        # 查询按钮
        search_btn = tk.Button(btn_frame, text="查询", width=10, 
                             command=lambda: self.perform_search(
                                 order_num_entry.get(),
                                 sender_entry.get(),
                                 dialog
                             ))
        search_btn.pack(side="left", padx=10)
        
        # 取消按钮
        cancel_btn = tk.Button(btn_frame, text="取消", width=10, command=dialog.destroy)
        cancel_btn.pack(side="left", padx=10)
        
        dialog.mainloop()
    
    def perform_search(self, order_num, sender, dialog):
        """执行订单查询"""
        # 清空现有选择
        for item in self.order_tree.selection():
            self.order_tree.selection_remove(item)
        
        # 根据条件查找订单
        if order_num:
            self.cursor.execute("""
                SELECT orders.id, order_number, sender, receiver, weight, 
                       origin.name, destination.name, status, created_at
                FROM orders
                JOIN sites AS origin ON orders.origin_site = origin.id
                JOIN sites AS destination ON orders.destination_site = destination.id
                WHERE order_number LIKE ?
            """, (f"%{order_num}%",))
        elif sender:
            self.cursor.execute("""
                SELECT orders.id, order_number, sender, receiver, weight, 
                       origin.name, destination.name, status, created_at
                FROM orders
                JOIN sites AS origin ON orders.origin_site = origin.id
                JOIN sites AS destination ON orders.destination_site = destination.id
                WHERE sender LIKE ?
            """, (f"%{sender}%",))
        else:
            messagebox.showwarning("警告", "请输入订单号或发件人！")
            return
        
        orders = self.cursor.fetchall()
        
        if not orders:
            messagebox.showinfo("查询结果", "没有找到匹配的订单！")
            return
        
        # 在表格中高亮显示找到的订单
        for item in self.order_tree.get_children():
            values = self.order_tree.item(item)['values']
            for order in orders:
                if values[0] == order[0]:
                    self.order_tree.selection_add(item)
        
        messagebox.showinfo("查询结果", f"找到 {len(orders)} 个匹配的订单！")
        dialog.destroy()
    
    def on_closing(self):
        """关闭窗口时关闭数据库连接"""
        if messagebox.askokcancel("退出", "确定要退出系统吗？"):
            self.conn.close()
            self.root.destroy()

if __name__ == "__main__":
    root = tk.Tk()
    app = DroneDeliverySystem(root)
    root.mainloop()